package com.bw.controller.bil;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.entity.bil.PiInvoice;
import com.bw.entity.bil.PiInvoiceLog;
import com.bw.entity.order.PiOrder;
import com.bw.resp.ResponseResult;
import com.bw.service.bil.IPiInvoiceLogService;
import com.bw.service.bil.IPiInvoiceService;
import com.bw.service.order.IPiOrderService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yzz
 * @since 2020-06-27
 */
@RestController
@RequestMapping("/bil")
public class PiInvoiceController {
    @Autowired
    private IPiInvoiceService invoiceService;
    @Autowired
    private IPiInvoiceLogService invoiceLogService;
    @Autowired
    private IPiOrderService iPiOrderService;
    //定义日志工具
    private final Logger logger = LoggerFactory.getLogger(PiInvoiceController.class);

    /**
     * 发票页面查询列表
     *
     * @param num
     * @param size
     * @param id
     * @param invoice
     * @return
     */
    @PostMapping("/list/{num}/{size}/{id}")
    public ResponseResult list(@PathVariable("num") int num, @PathVariable("size") int size
            , @PathVariable("id") Long id, @RequestBody PiInvoice invoice) {
        logger.info("发票查询查询开始");
        ResponseResult re = new ResponseResult(false, 400, "发票查询失败");
        try {
            QueryWrapper qw = new QueryWrapper();
            qw.ne("state", 0);
            qw.ne("is_delete", 1);//排除已经删除的数据
            qw.orderByDesc("update_date");//根据修改时间倒序排序
            if (id != null) {//只展示当前登录用户名下的客户
                if(id!=1){
                    qw.eq("customer_id", id);
                }
            }
            if (invoice.getCreateDate() != null) {//根据创建时间倒序排序
                qw.orderByDesc("create_date");
            }
            if (invoice.getState() != null) {//根据状态查询
                qw.eq("state", invoice.getState());
            }
            if (invoice.getCode() != null) {//根据编号查询
                qw.like("code", "%" + invoice.getCode() + "%");
            }
            if (invoice.getMin() != null && invoice.getMax() != null) {//查询订单创建时间的区间
                qw.between("create_date", invoice.getMin(), invoice.getMax());
            }
            PageHelper.startPage(num, size);//开启分页
            List bilList = invoiceService.list(qw);//查询list
            PageInfo pageInfo = new PageInfo(bilList);//分页后数据
            re.setResult(pageInfo);//存储
            logger.info("发票查询查询结束");
            return re;
        } catch (Exception e) {
            logger.error("发票查询查询失败,{}", e.toString());
            return re;
        }
    }

    /**
     * 审核发票
     *
     * @param up,name,userid,invoice:
     * @Description:修改发票状态
     * @Author: 杨祯祯
     * @Date: 2020/6/27
     * @return: com.bw.resp.ResponseResult
     */
    @PostMapping("/updateAndSave/{up}/{name}/{userid}")
    public ResponseResult updateAndSave(@PathVariable("up") Integer up, @PathVariable("name") String name,
                                        @PathVariable("userid") Long userid, @RequestBody PiInvoice invoice) {
        logger.info("审核发票开始");
        ResponseResult re = new ResponseResult(false, 400, "操作失败");
        try {
            //修改并保存
            PiInvoice byId = invoiceService.getById(invoice.getId());//找到对应的订单
            byId.setState(up);
            byId.setUpdateDate(new Date());//发票更新时间
            invoiceService.saveOrUpdate(byId);
            invoice.setState(up);
            invoiceService.saveOrUpdate(invoice);
            if(invoice.getState()==2){
                //总价减去开票额度
                logger.info("订单总价减少");
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("code", invoice.getCode());
                PiOrder piOrder = iPiOrderService.getOne(queryWrapper);
                BigDecimal money = new BigDecimal('0');
                money = money.add(invoice.getAmount());//发票开票金额
                BigDecimal price = piOrder.getPrice();//订单总金额
                price=price.subtract(money);//减法
                piOrder.setPrice(price);//总金额减少
                iPiOrderService.saveOrUpdate(piOrder);//保存
                PiInvoice piInvoice = new PiInvoice();
                piInvoice.setUpdateDate(new Date());
                piInvoice.setUpdateUser(userid);
                invoiceService.save(piInvoice);
            }
            logger.info("发票操作记录添加");
            PiInvoiceLog invoiceLog = new PiInvoiceLog();
            if (up == 2) {
                invoiceLog.setRemarks("发票已通过");
            } else if (up == 3) {
                invoiceLog.setRemarks("发票已驳回");
            }
            invoiceLog.setInvoiceid(invoice.getId());
            invoiceLog.setUserid(userid);
            invoiceLog.setUsername(name);
            invoiceLog.setCreatetime(new Date());
            invoiceLogService.save(invoiceLog);
            re.setSuccess(true);
            re.setMessage("操作成功");
            re.setCode(200);
            logger.info("审核发票结束");
            return re;
        } catch (Exception e) {
            logger.error("发票根据状态id修改错误,{}", e.toString());
            return re;
        }
    }

    /**发票回显
     * @param id:
     * @Description:根据id回显发票
     * @Author: 杨祯祯
     * @Date: 2020/6/27
     * @return: com.bw.resp.ResponseResult
     **/
    @PostMapping("/getById/{id}")
    public ResponseResult getBilById(@PathVariable("id") Long id) {
        logger.info("发票回显查询开始");
        ResponseResult re = new ResponseResult(false, 400, "查询失败");
        try {
            PiInvoice byId = invoiceService.getById(id);
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("code", byId.getCode());
            PiOrder piOrder = iPiOrderService.getOne(queryWrapper);

            Map map = new HashMap();
            map.put("invoice", byId);
            map.put("piOrder", piOrder);
            re.setSuccess(true);
            re.setMessage("查询成功");
            re.setCode(200);
            re.setResult(map);//存储
            logger.info("发票回显查询结束");
            return re;
        } catch (Exception e) {
            logger.error("发票回显查询失败,{}", e.toString());
            return re;
        }
    }

    /**
     * 客户端根据id删除发票
     *并还原订单价格
     * @param up,name,userid,invoice:
     * @Description:据id删除发票
     * @Author: 杨祯祯
     * @Date: 2020/6/27
     * @return: com.bw.resp.ResponseResult
     */
    @PostMapping("/delBillByid/{id}/{up}/{loginUser}/{costomerId}")
    public ResponseResult delBillByid(@PathVariable("id") Long id, @PathVariable("up") Integer up,
                                      @PathVariable("loginUser") String name, @PathVariable("costomerId") Long userid) {
        logger.info("发票根据id删除开始");
        ResponseResult re = new ResponseResult(false, 400, "删除成功");
        try {
            //修改并保存
            PiInvoice byId = invoiceService.getById(id);//找到对应的订单
            byId.setIsDelete(up);//修改为删除
            invoiceService.saveOrUpdate(byId);
            //总价还原
            logger.info("订单总价还原");
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("code", byId.getCode());
            PiOrder piOrder = iPiOrderService.getOne(queryWrapper);//需要找到该客户的所有已报价订单的价格总和
            BigDecimal money = new BigDecimal('0');
            money = money.add(byId.getAmount());//发票开票金额
            BigDecimal price = piOrder.getPrice();//订单总金额
            price=price.add(money);
            piOrder.setPrice(price);//还原总金额
            iPiOrderService.saveOrUpdate(piOrder);//保存
            //0未提交1已提交2通过3被驳回4已邮寄5已查收
            logger.info("发票操作记录添加");
            PiInvoiceLog invoiceLog = new PiInvoiceLog();
            invoiceLog.setRemarks("发票已删除 ");
            invoiceLog.setInvoiceid(id);
            invoiceLog.setUserid(userid);
            invoiceLog.setUsername(name);
            invoiceLog.setCreatetime(new Date());
            invoiceLogService.save(invoiceLog);
            re.setSuccess(true);
            re.setMessage("删除成功");
            re.setCode(200);
            logger.info("发票根据id删除结束");
            return re;
        } catch (Exception e) {
            logger.error("发票根据id删除失败,{}", e.toString());
            return re;
        }
    }

    /**
     * 根据id修改发票状态
     *
     * @param up,name,userid:
     * @Description:根据id修改发票状态
     * @Author: 杨祯祯
     * @Date: 2020/6/27
     * @return: com.bw.resp.ResponseResult
     */
    @PostMapping("/updateStateByid/{id}/{up}/{name}/{userid}")
    public ResponseResult updateStateByid( @PathVariable("id") Long id, @PathVariable("up") Integer up,
                                          @PathVariable("name") String name, @PathVariable("userid") Long userid) {
        logger.info("发票根据id修改开始");
        ResponseResult re = new ResponseResult(false, 400, "修改失败");
        try {
            //修改并保存
            PiInvoice byId = invoiceService.getById(id);//找到对应的发票
            byId.setState(up);
            byId.setUpdateDate(new Date());//发票更新时间
            invoiceService.saveOrUpdate(byId);
            //0未提交1已提交2通过3被驳回4已邮寄5已查收
            logger.info("发票操作记录添加");
            PiInvoiceLog invoiceLog = new PiInvoiceLog();
            if (up == 2) {
                invoiceLog.setRemarks("发票已通过");
            } else if (up == 3) {
                invoiceLog.setRemarks("发票已驳回");
            } else if (up == 4) {
                invoiceLog.setRemarks("发票邮寄");
            } else if (up == 5) {
                invoiceLog.setRemarks("发票已查收 ");
            }
            invoiceLog.setInvoiceid(id);
            invoiceLog.setUserid(userid);
            invoiceLog.setUsername(name);
            invoiceLog.setCreatetime(new Date());
            invoiceLogService.save(invoiceLog);
            re.setSuccess(true);
            re.setMessage("修改成功");
            re.setCode(200);
            logger.info("发票根据id修改结束");
            return re;
        } catch (Exception e) {
            logger.error("发票根据id修改失败,{}", e.toString());
            return re;
        }
    }

    /**
     * 申请发票
     *
     * @param costomerId:
     * @Description:申请发票
     * @Author: 王诗琪
     * @Date: 2020/6/27
     * @return: com.bw.resp.ResponseResult
     */
    @PostMapping("/saveinvoice/{costomerId}/{code}")
    public ResponseResult saveinvoice(@PathVariable("costomerId") Long costomerId, @PathVariable("code") String code, @RequestBody PiInvoice piInvoice) {
        logger.info("申请发票开始");
        ResponseResult re = new ResponseResult(false, 400, "发送失败");
        try {
            piInvoice.setState(0);
            piInvoice.setCreateDate(new Date());
            piInvoice.setCustomerId(costomerId);
            piInvoice.setIsDelete(0);
            piInvoice.setCode(code);
            invoiceService.save(piInvoice);

            PiInvoiceLog piInvoiceLog = new PiInvoiceLog();
            piInvoiceLog.setUserid(costomerId);
            piInvoiceLog.setUsername(piInvoice.getReceiver());
            piInvoiceLog.setInvoiceid(piInvoice.getId());
            piInvoiceLog.setCreatetime(new Date());
            piInvoiceLog.setRemarks("申请发票");
            invoiceLogService.save(piInvoiceLog);
            re.setMessage("申请发票成功");
            logger.info("申请发票结束");
            return re;
        } catch (Exception e) {
            logger.error("申请发票,{}", e.toString());
            re.setMessage("申请发票失败" + e.toString());
        }
        return re;
    }

    /**
     * 发票页面查询列表
     *
     * @param num
     * @param size
     * @param id
     * @param invoice
     * @return
     */
    @PostMapping("/blist/{num}/{size}/{id}")
    public ResponseResult blist(@PathVariable("num") int num, @PathVariable("size") int size
            , @PathVariable("id") Long id, @RequestBody PiInvoice invoice) {
        logger.info("发票查询查询开始");
        ResponseResult re = new ResponseResult(false, 400, "发票失败");
        try {
            QueryWrapper qw = new QueryWrapper();
            qw.ne("is_delete", 1);//排除已经删除的数据
            if (id != null) {//只展示当前登录用户名下的客户
                if(id!=1){
                    qw.eq("customer_id", id);
                }
            }
            if (invoice.getCreateDate() != null) {//根据创建时间倒序排序
                qw.orderByDesc("create_date");
            }
            if (invoice.getState() != null) {//根据状态查询
                qw.eq("state", invoice.getState());
            }
            if (invoice.getCode() != null) {//根据编号查询
                qw.like("code", "%" + invoice.getCode() + "%");
            }
            if (invoice.getMin() != null && invoice.getMax() != null) {//查询订单创建时间的区间
                qw.between("create_date", invoice.getMin(), invoice.getMax());
            }
            PageHelper.startPage(num, size);//开启分页
            List bilList = invoiceService.list(qw);//查询list
            PageInfo pageInfo = new PageInfo(bilList);//分页后数据
            re.setResult(pageInfo);//存储
            logger.info("发票查询查询结束");
            return re;
        } catch (Exception e) {
            logger.error("发票查询查询失败,{}", e.toString());
            return re;
        }
    }

}
